package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.dto.LoginDto;
import com.heima.admin.entity.AdUser;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.IAdUserService;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppJwtUtil;
import com.heima.common.util.MD5Utils;
import com.mysql.jdbc.Security;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 管理员用户信息表 服务实现类
 * </p>
 *
 * @author mcm
 * @since 2022-03-11
 */
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements IAdUserService {


    @Override
    public ResponseResult login(LoginDto dto) {
        //首先判断参数是否齐全
        if (dto == null || dto.getPassword() == null || dto.getName() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //接下来去数据库查询有无该用户,就通过用户名搜索出该用户，然后再根据传来的密码+盐通过MD5
        //和数据库的密码比较再进行下一步的判断
        LambdaQueryWrapper<AdUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AdUser::getName,dto.getName());
        AdUser adUser = getOne(queryWrapper);
        if(adUser==null)
        {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //接下来准备比较md5密码,盐放数据库是不是不安全。。
       String pwdStr= dto.getPassword()+ adUser.getSalt();
        String md5Pwd = DigestUtils.md5DigestAsHex(pwdStr.getBytes());
        //如果不相等直接返回，不返回就开始作token拉
        if(!md5Pwd.equals(adUser.getPassword()))
        {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //到这一步，开始制作token
        Map<String, Object> claims = new HashMap<String, Object>();
        claims.put("userId",adUser.getId());
        claims.put("userName",adUser.getName());
        String token = AppJwtUtil.getToken(claims);
        HashMap<String, Object> map = new HashMap<>();
        adUser.setPassword(null);
        adUser.setPhone(null);
        adUser.setSalt(null);
        map.put("user",adUser);
        map.put("token",token);
        return ResponseResult.okResult(map);
    }
}
